#include "SubscriberListener.h"

SubscriberListener::SubscriberListener() :
    _debug(false),
    _data(""),
    _dataWritingFlag(false)
{
    cout << "[SubscriberListener::SubscriberListener] Creating a subscriber listener..." << endl;
}

SubscriberListener::~SubscriberListener(void) {
    if(_debug)
        cout << "[SubscriberListener::~SubscriberListener] Instance destroyed." << endl;
}

void SubscriberListener::OnMessage(vhpubsub::Session* session, const vhpubsub::Message* msg) {
    try {
        _dataWritingFlag = true;

		const void* msgData = msg->GetDataBuf();
		size_t msgSize = msg->GetDataSize();
		std::string data;
        data.assign((char*)msgData, msgSize);
        
        if(false) {
            cout << msg->GetSubject() << " " << data.c_str() << endl;
        }
        
        _data.append("{");
        _data.append(msg->GetSubject());
        _data.append(" \"");
        _data.append(data);
        _data.append("\"");
        _data.append("} ");

        _dataWritingFlag = false;
    }
    catch (const runtime_error& e) {
        cerr << "Exception: " << e.what() << endl;
	}
	catch (...) {
        cerr << "Exception: unknown error" << endl;
	}
}

std::string SubscriberListener::getData() {
    if(_dataWritingFlag) {
        return "";
    } else {
        std::string r;
        r.append(_data);
        _data = "";
        return r;
    }
}

void SubscriberListener::OnSessionEvent(vhpubsub::Session* session, const vhpubsub::SessionEvent* event) {
    if (event->GetType() == vhpubsub::SessionEvent::DISCONNECT && event->GetSessionId() == session->GetId()) {
		cout << "[SubscriberListener::OnSessionEvent] Disconnected." << endl;
		//exit(0);
	}
}

void SubscriberListener::setDebugMode(const bool &debug) {
    _debug = debug;
}